package com.dataart.productshop.file.utils;

import org.apache.commons.io.IOUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;


public class ResizeImage {

	private static final int IMG_WIDTH = 512;
	private static final int IMG_HEIGHT = 512;

	public static void resizeImage(String filePath) throws IOException {
		BufferedImage bi = ImageIO.read(new File(filePath));
		int type = bi.getType() == 0? BufferedImage.TYPE_INT_ARGB : bi.getType();
		ImageIO.write(resizeImageWithHint(bi, type), "jpg", new File(filePath));
	}
	
	public static BufferedImage resizeStreamImage(InputStream imageStream){
		BufferedImage bi = null;
		try {
			bi = ImageIO.read(imageStream);
			if(bi.getHeight() > IMG_HEIGHT || bi.getWidth() > IMG_WIDTH){
			//TODO: NPE is comming here. please figure out how to reproduce is by test and write this test _before_ fixing the problem
				int type = bi.getType() == 0? BufferedImage.TYPE_INT_ARGB : bi.getType();
				bi = resizeImageWithHint(bi, type);
			}
		} catch (IOException e) {
			System.err.println("error in reading stream into BufferedImage");
		}finally{
            IOUtils.closeQuietly(imageStream);
        }
		return bi;
	}
	
	private static BufferedImage resizeImageWithHint(BufferedImage originalImage, int type){
		BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
		g.dispose();	
		g.setComposite(AlphaComposite.Src);
	 
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
		RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g.setRenderingHint(RenderingHints.KEY_RENDERING,
		RenderingHints.VALUE_RENDER_QUALITY);
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
		RenderingHints.VALUE_ANTIALIAS_ON);
	 
		return resizedImage;
	}
	
	
}
